from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import base64
import time
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.common.by import By
import sys

if __name__ == '__main__':
    if len(sys.argv) < 4:
        print("Usage: python appproxy.py <udid> <appium_address> <hash_id>")
        sys.exit(1)
    udid = sys.argv[1] #"127.0.0.1:9614"
    appium_address = sys.argv[2]    #"http://127.0.0.1:4723"
    hashid = sys.argv[3]
    caps = {
        "platformName": "Android",
        "automationName": "uiautomator2",
        "udid": udid,
        "appPackage": "com.github.kr328.clash",
        "appActivity": "com.github.kr328.clash/.MainActivity",
        "noReset": True,
        "chromedriverExecutable": "/root/chromedriver/chromedriver",
        "autoGrantPermissions": True,
        "uiautomator2ServerLaunchTimeout": 120000,  # 增加服务器启动超时
        "adbExecTimeout": 120000,  # 增加ADB执行超时
    }

    driver = webdriver.Remote(appium_address, caps)

    # 启动指定 Activity
    driver.start_activity("com.github.kr328.clash", "com.github.kr328.clash/.MainActivity")
    # //android.widget.Button[@text="Agree and continue"]
    #hashid = "jmzQjDA9"
    try:
        expected_texts = {
            "zh": "配置",
            "en": "Profile",
            "jp": "設定",  # 举例
            # 你可以补充更多语言
        }

        els = driver.find_elements(AppiumBy.ID, "com.github.kr328.clash:id/text_view")
        for el in els:
            if el.text in expected_texts.values():
                print("定位到目标元素，其 text 是:", el.text)
                el.click()
                break
        else:
            raise Exception("没有找到匹配语言的 “配置” 项")
    except:
        print("未找到配置按钮")


    def find_item_with_number(target_number: str, max_swipes: int = 5):
        for i in range(max_swipes):
            # 获取当前可见的 root_view 项
            items = driver.find_elements(
                AppiumBy.ID, "com.github.kr328.clash:id/root_view"
            )
            for item in items:
                try:
                    txt_elem = item.find_element(
                        AppiumBy.CLASS_NAME, "android.widget.TextView"
                    )
                    if txt_elem.text == target_number:
                        return item
                except Exception:
                    continue
        return None


    def create_new_profile():
        try:
            add_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '//android.widget.ImageView[@resource-id="com.github.kr328.clash:id/add_view"]'
            )))
            add_btn.click()
            url_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '//androidx.recyclerview.widget.RecyclerView[@resource-id="com.github.kr328.clash:id/main_list"]/android.widget.LinearLayout[2]'
            )))
            url_btn.click()
            name_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '(//android.widget.FrameLayout[@resource-id="com.github.kr328.clash:id/action_view"])[1]'
            )))
            name_btn.click()
            wait = WebDriverWait(driver, 10)
            # 等待 EditText 出现
            edit = wait.until(
                EC.presence_of_element_located(
                    (AppiumBy.XPATH, "//android.widget.EditText[@resource-id='com.github.kr328.clash:id/text_field']")
                )
            )
            # 可选：清空已有文本
            edit.clear()
            # 输入 “2”
            edit.send_keys(hashid)
            save_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '//android.widget.Button[@resource-id="android:id/button1"]'
            )))
            save_btn.click()
            url_input_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '(//android.widget.FrameLayout[@resource-id="com.github.kr328.clash:id/action_view"])[2]'
            )))
            url_input_btn.click()
            url = "https://clp.jtcloud.icu/api/v1/proxy/clash_subscribe?token=" + hashid
            # //android.widget.EditText[@resource-id="com.github.kr328.clash:id/text_field"]
            url_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((
                AppiumBy.XPATH,
                '//android.widget.EditText[@resource-id="com.github.kr328.clash:id/text_field"]'
            )))
            url_input.clear()
            url_input.send_keys(url)
            save_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '//android.widget.Button[@resource-id="android:id/button1"]'
            )))
            save_btn.click()
            whole_save_btn_wrap = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '//android.widget.FrameLayout[@resource-id="com.github.kr328.clash:id/action_layout"]'
            )))
            whole_save_btn_wrap.find_element(
                AppiumBy.XPATH,
                '//android.widget.ImageView'
            ).click()
        except:
            print("未找到创建按钮")


    def chose_profile():
        # 等待 RecyclerView 出现
        wait = WebDriverWait(driver, 20)
        recycler = wait.until(
            EC.presence_of_element_located(
                (AppiumBy.ID, "com.github.kr328.clash:id/main_list")
            )
        )
        target_item = find_item_with_number(hashid, max_swipes=3)
        if not target_item:
            raise Exception(f"未找到 text 为 {hashid} 的条目")

        # 在找到的 item 中，定位 RadioButton 并点击
        radio_btn = target_item.find_element(
            AppiumBy.ID, "com.github.kr328.clash:id/icon_view"
        )
        radio_btn.click()


    try:
        chose_profile()
    except:
        print("未找到目标元素")
        try:
            create_new_profile()
            chose_profile()
        except:
            print("未找到创建按钮")
        # create_new_profile()


    def get_main_btns():
        btns = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((
            AppiumBy.XPATH,
            '//android.widget.ScrollView/android.widget.LinearLayout/androidx.cardview.widget.CardView'
        )))
        return btns


    closebtn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
        AppiumBy.ID,
        'com.github.kr328.clash:id/activity_bar_close_view'
    )))
    closebtn.click()
    btns = get_main_btns()
    if len(btns) > 0:
        btns[0].click()
    else:
        print("未找到按钮")
    # btns = get_main_btns()
    # if len(btns) > 2:
    #     btns[1].click()
    # else:
    #     print("未找到第二个按钮")

    driver.quit()

